import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { Text, View, StyleSheet, Alert, ScrollView, ActivityIndicator, TouchableOpacity } from 'react-native';
import { Icon, List, ListItem, Button, SearchBar } from 'react-native-elements';
import Loader from './widgets/Loader';
import RefreshScrollView from './widgets/RefreshScrollView';
import InfiniteList from './widgets/InfiniteList';
import { listDevices, disconnect } from './printerUtils';
import { primaryColor, toast, isIOS, loadMoreData, executor, getDirection } from './utils';
import moment from 'moment';
import { MyJobQuery } from './graphql';

const styles = StyleSheet.create({
  button: {
    marginVertical: 32
  },
  config: {
    margin: 16
  },
  header: {
    padding: 8
  },
  list: {
    marginTop: 0
  },
  spinner: {
    margin: 64
  },
  padding: {
    marginVertical: 32
  }
});

class JobPollPage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    return {
      title: screenProps.chinese?`可选工作`:`Available Jobs`,
      tabBarLabel: screenProps.chinese?`可选工作`:`Available Jobs`,
      tabBarIcon: ({tintColor}) => <Icon name='playlist-add' color={tintColor} size={24}/>
    };
  }
  state = { }
  onSelectDate = ({year, month, day}) => {
    const date = moment([year, month-1, day]).toDate().toString();
    this.props.navigation.setParams({date});
  }
  onSearch = (search) => {
    this.props.refetch({search})
      .then(() => this.setState({searching: false}));
    this.setState({searching: true});
  }
  renderItem = ({item}) => {
    const {shipping, pricing: {details}, orderTypeDescription} = item;
    return <ListItem subtitle={`${orderTypeDescription}, ${this.props.screenProps.chinese?`开始时间`:`Start from`} ${shipping.displayDate}\r\n${shipping.address}, ${shipping.postalCode}\r\n[${shipping.contactName}]`}
      title={`${details[0].description} x ${details[0].quantity} ${details[0].quantityUnit}${details[0].subDescription?`. ${details[0].subDescription}`:''}`}
      titleNumberOfLines={4} subtitleNumberOfLines={10} onPress={()=>this.getJob(item)} hideChevron/>;
  }
  getJob = ({displayId, shipping, pricing: {details}, orderTypeDescription}) => {
    Alert.alert(
      this.props.screenProps.chinese?`确定要领取这份工作么？`:`Are you sure you want accpet this job?`,
      `${details[0].description} x ${details[0].quantity} ${details[0].quantityUnit}${details[0].subDescription?`. ${details[0].subDescription}`:''}\r\n${orderTypeDescription}\r\n${this.props.screenProps.chinese?'开始时间':'Start from'}: ${shipping.displayDate}\r\n${shipping.address} [${shipping.contactName}]`,
      [
        {text: this.props.screenProps.chinese?'取消':'Cancel'},
        {text: this.props.screenProps.chinese?'接受工作':'Accept This Job', onPress: () => {
          executor(this.props.selfAssignOrder, {orderNumber:displayId,date:shipping.date})
            .then(({res}) => {
              if (res) {
                toast(this.props.screenProps.chinese?'工作获取成功':'Job accepted', true);
              }
            });
          toast(this.props.screenProps.chinese?'工作获取中，请稍后...':'Accepting the job, please wait...', true);
        }},
      ],
      { cancelable: true }
    );
  }
  render() {
    const { screenProps, refetch, fetchMore, loading, orderPool } = this.props;
    const { chinese } = screenProps;

    return (
      <RefreshScrollView refetch={refetch}>
        <SearchBar inputStyle={{height:50}} lightTheme onChangeText={this.onSearch} placeholder={chinese?'按地址查询工作':'Search by location'}
          showLoadingIcon={this.state.searching}/>
        {(loading&&!this.state.searching)?<ActivityIndicator style={styles.spinner}/>:
          <InfiniteList top datas={orderPool&&orderPool.filter((order,index)=>!order.seriesId||(orderPool.findIndex(item=>item.seriesId===order.seriesId)===index))} loading={loading}
            refetch={refetch} fetchMore={fetchMore} containerStyle={styles.availableJob}
            renderItem={this.renderItem} renderHeader={this.renderHeader} chinese={chinese}/>
        }
        <View style={styles.padding}/>
      </RefreshScrollView>
    );
  }
}

const OrderFragment = gql`
  fragment OrderFragment on Order {
    id
    displayId
    orderTypeDescription
    seriesId
    status {
      statusId
    }
    shipping {
      date
      displayDate
      address
      contactName
      postalCode
    }
    pricing {
      details {
        description
        quantity
        quantityUnit
        subDescription
      }
    }
  }
`;

const JobPollQuery = gql`
  query JobPollQuery($date:String!,$endDate:String,$search:String,$offset:Int,$limit:Int,$type:String!) {
    orderPool(date:$date,endDate:$endDate,search:$search,offset:$offset,limit:$limit,type:$type) {
      ...OrderFragment
    }
  }
  ${OrderFragment}
`;

function getVariables({state:{params}}) {
  const {search, offset=0, limit, date} = params||{};
  return {
    search,
    offset,
    limit,
    date: moment(date).toDate().toString(),
    endDate: moment(date).add(1,'months').toDate().toString(),
    type: 'houseclean'
  };
}

export default compose(
  graphql(JobPollQuery, {
    options: ({navigation}) => ({variables: getVariables(navigation)}),
    props: ({data:{orderPool, loading, fetchMore, refetch}}) => {
      return {
        orderPool,
        loading,
        refetch,
        fetchMore: () => loadMoreData(fetchMore, orderPool, 'orderPool')
      };
    }
  }),
  graphql(gql`
    mutation selfAssignOrder($orderNumber:Int!){
      selfAssignOrder(orderNumber:$orderNumber) {
        id
      }
    }
  `, {
    props: ({ownProps:{navigation}, mutate}) => {
      return {
        selfAssignOrder: ({orderNumber, date}) => mutate({
          variables:{orderNumber},
          refetchQueries: ['MyJobQuery', 'JobPollQuery']
        })
      }
    }
  })
)(JobPollPage);

